#! /usr/bin/env python3
import time
import os

from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.support.wait import WebDriverWait
import requests


class UiKeyWords:
    """
    UI操作的关键字封装
    """

    def __init__(self, driver: WebDriver) -> None:
        """初始化操作"""
        self.driver = driver

    def open_page(self, url: str = '') -> None:
        """打开网页"""
        self.driver.get(url)

    def find_element(self, by: str = 'css selector', val: str = "") -> WebElement:
        """显式等待定位元素"""
        return WebDriverWait(self.driver, 10, 0.5).until(lambda x: x.find_element(by, val))

    def send_keys(self, by: str = 'css selector', val: str = '', text: str = '') -> None:
        """输入文本信息"""
        element = self.find_element(by, val)
        element.clear()
        element.send_keys(text)

    def click(self, by: str = 'css selector', val: str = ''):
        """点击"""
        self.find_element(by, val).click()

    def submit(self, by: str = 'css selector', val: str = ''):
        """提交表单"""
        self.find_element(by, val).submit()

    def verify_source(self, exp: str = ''):
        """断言"""
        time.sleep(2)
        assert exp in self.driver.page_source

    def verify_alert(self, exp: str = ''):
        """断言弹窗内容"""
        time.sleep(3)
        msg = self.driver.switch_to.alert.text
        assert exp in msg

    def screenshot(self):
        """截图"""
        return self.driver.get_screenshot_as_png()


class ApiKeyWords:
    """
    API操作的关键字封装
    """

    def __init__(self, base_url: str) -> None:
        """初始化根地址"""
        self.base_url = base_url

    def get(self, path: str, **kwargs):
        return requests.get(self.base_url+path, **kwargs)

    def post(self, path: str, **kwargs):
        return requests.post(self.base_url+path, **kwargs)
